1
Easy2Siksha
GNDU Question Paper-2024
B.A 2
nd
Semester
COMPUTER SCIENCE
(Programming Using C)
Time Allowed: 3 Hours Maximum Marks: 75
Note: There are Eight questions of equal marks. Candidates are required to attempt any Four
questions.
SECTION-A
1. What is a Character Code? What are the different types of character code?
2. What is Problem Analysis? Explain any two tools for problem analysis.
SECTION-B
3. What is a Syntax Error? How is it different from a logical error? Give three examples of each of
them.
4. With the help of examples, state the different operators in C.
SECTION-C
5. Write pseudo code for arranging numbers in a sorted way in an array.
6. Explain any five string handling functions using different examples.
2
Easy2Siksha
SECTION-D
7. What are the different ways of passing arguments to a function? Explain with the help of an
example.
8. Explain the scope and lifetime of a variable in the context of different storage classes.
GNDU Answer Paper-2024
B.A 2
nd
Semester
COMPUTER SCIENCE
(Programming Using C)
Time Allowed: 3 Hours Maximum Marks: 75
Note: There are Eight questions of equal marks. Candidates are required to attempt any Four
questions.
SECTION-A
1. What is a Character Code? What are the different types of character code?
Ans: Character Code and Its Types
What is a Character Code?
A character code is a system of representing letters, numbers, symbols, and other characters in a
way that computers can understand. Computers can only process information in the form of
numbers (binary digits: 0s and 1s). However, humans use a variety of symbols, letters, and numbers
to communicate. To bridge this gap, character codes are used to convert human-readable text into
machine-readable numeric values.
For example, when you press the letter "A" on your keyboard, the computer does not understand
"A" as we do. Instead, it recognizes "A" as a specific number in binary format. This numeric
representation is called a character code.
3
Easy2Siksha
Why Do We Need Character Codes?
Character codes are essential because:
1. They allow computers to store and process text data.
2. They help different devices (like computers, phones, printers) understand the same
characters.
3. They enable communication between systems using different languages and symbols.
Types of Character Codes
There are several character coding systems used in computers. Some of the most common ones
include:
1. ASCII (American Standard Code for Information Interchange)
2. Extended ASCII
3. EBCDIC (Extended Binary Coded Decimal Interchange Code)
4. Unicode
5. ISCII (Indian Standard Code for Information Interchange)
Let’s discuss each of them in detail.
1. ASCII (American Standard Code for Information Interchange)
ASCII is one of the earliest and most commonly used character coding systems. It was developed in
1963 and uses 7 bits to represent characters. Since a bit (binary digit) can be either 0 or 1, a 7-bit
code can represent 2⁷ = 128 different characters.
ASCII Character Representation:
The numbers 0 to 9 are represented as ASCII codes 48 to 57.
The uppercase letters A to Z are represented as ASCII codes 65 to 90.
The lowercase letters a to z are represented as ASCII codes 97 to 122.
Special symbols like @, #, $, %, & have their own ASCII values.
Limitations of ASCII:
1. Limited Character Set ASCII can only represent 128 characters, which is not enough for
languages with special symbols (like Chinese, Hindi, Arabic, etc.).
2. No Direct Support for Non-English Characters Languages other than English require more
characters than ASCII can provide.
2. Extended ASCII
To overcome the limitations of standard ASCII, an Extended ASCII version was introduced. It uses 8
bits instead of 7, which allows for 256 characters (2⁸ = 256) instead of 128.
4
Easy2Siksha
Benefits of Extended ASCII:
It includes additional symbols, mathematical characters, and graphical characters.
It supports some non-English letters, such as é, ñ, ç.
Example:
Character
Extended ASCII Code (Decimal)
Ç
128
é
130
ñ
164
£
156
Limitations:
It still does not support all world languages.
Different systems use different versions of Extended ASCII, leading to compatibility issues.
3. EBCDIC (Extended Binary Coded Decimal Interchange Code)
EBCDIC is another character coding system developed by IBM for its mainframe computers. Unlike
ASCII, which is widely used, EBCDIC is mainly limited to IBM systems.
Key Features:
Uses 8 bits, allowing for 256 characters.
Not commonly used outside IBM mainframes.
More complex than ASCII because character order is not sequential (for example, ‘A’ is not
necessarily next to ‘B’ in the code).
Example:
Character
EBCDIC Code (Decimal)
A
193
B
194
a
129
Limitations:
Not used in most modern computing systems.
More complex and less human-friendly than ASCII.
5
Easy2Siksha
4. Unicode
Unicode is the most widely used character encoding system today. Unlike ASCII and EBCDIC, which
have limited characters, Unicode is designed to support all languages around the world, including
English, Chinese, Hindi, Arabic, and many more.
Key Features:
Unicode uses different encoding formats:
o UTF-8 (8-bit encoding, most commonly used)
o UTF-16 (16-bit encoding, supports more characters)
o UTF-32 (32-bit encoding, supports all Unicode characters)
Unicode can represent over 1 million characters.
Example:
Character
Unicode (UTF-8) Code (Hex)
A
0041
(Hindi)
0939
(Chinese)
4E2D
󺅕󺅓󺅖󺅗󺅘󺅔 (Emoji)
1F60A
Benefits of Unicode:
Supports all languages.
Used in modern applications like websites, databases, and programming.
Compatible with ASCII (UTF-8 encoding keeps ASCII characters the same).
Limitations:
Unicode files take up more storage space than ASCII.
5. ISCII (Indian Standard Code for Information Interchange)
ISCII was developed to support Indian languages such as Hindi, Punjabi, Bengali, Tamil, Telugu, etc.
Key Features:
Uses 8-bit encoding like ASCII.
Allows representation of Indian scripts by adding modifications to the English alphabet.
Less commonly used now, as Unicode has replaced it.
6
Easy2Siksha
Example:
Character
ISCII Code (Hex)
B0
C7
Conclusion
Character codes are essential for computers to understand text. The most commonly used coding
systems are ASCII, Extended ASCII, EBCDIC, Unicode, and ISCII. Among these, Unicode is the most
versatile and widely used system, as it supports multiple languages and symbols.
Quick Summary of Character Codes:
Character Code
Characters Supported
Used For
ASCII
128
English letters and symbols
Extended ASCII
256
Additional symbols and characters
EBCDIC
256
IBM mainframes
Unicode
Over 1 million
Global languages, emojis, special characters
ISCII
Indian scripts
Indian languages
Understanding character codes helps programmers and developers handle text data efficiently in
different languages and applications. Unicode has become the standard for modern computing,
ensuring compatibility across various platforms and devices.
2. What is Problem Analysis? Explain any two tools for problem analysis.
Ans: Introduction to Problem Analysis
Problem analysis is the process of understanding a problem in detail before trying to solve it. In
computer science, especially in programming, problem analysis helps programmers break down
complex problems into smaller, manageable parts. It ensures that we clearly understand what the
problem is, what inputs are required, what outputs are expected, and what constraints exist.
7
Easy2Siksha
Imagine you are a detective solving a mystery. Before jumping to conclusions, you need to gather
clues, analyze patterns, and understand the situation completely. Similarly, in programming,
problem analysis helps you identify what needs to be done before writing any code.
Why is Problem Analysis Important?
1. Avoids Confusion: If a problem is not properly analyzed, a programmer may start coding
without a clear plan, leading to errors and inefficiency.
2. Saves Time: A well-analyzed problem ensures that programmers do not waste time
rewriting or debugging incorrect code.
3. Enhances Efficiency: When a problem is broken into smaller parts, it becomes easier to
solve.
4. Ensures Accuracy: Proper analysis helps in achieving the correct output and meeting the
user's requirements.
5. Reduces Errors: If a programmer understands the problem well, the chances of making
mistakes are reduced.
Steps in Problem Analysis
1. Identify the Problem: Clearly define what needs to be solved.
2. Determine Inputs and Outputs: Understand what data will be given (input) and what is
expected (output).
3. Identify Constraints: Find any limitations like memory, time, or specific conditions.
4. Break Down the Problem: Divide the problem into smaller, manageable parts.
5. Develop a Plan: Decide on the best approach to solve the problem.
6. Choose Tools: Use appropriate tools to analyze the problem effectively.
Two Important Tools for Problem Analysis
There are various tools used to analyze problems in programming. Two of the most commonly used
tools are Flowcharts and Pseudocode.
1. Flowcharts
A flowchart is a graphical representation of a problem-solving process. It uses different shapes like
ovals, rectangles, and diamonds to show the flow of steps in solving a problem.
Advantages of Flowcharts:
Helps in visualizing the problem clearly.
Shows the sequence of steps in a structured manner.
Makes debugging and modification easier.
Useful for explaining a solution to others.
8
Easy2Siksha
Basic Symbols Used in Flowcharts:
1. Oval: Represents the start and end of a program.
2. Rectangle: Represents a process or operation.
3. Diamond: Represents a decision (like Yes/No or True/False conditions).
4. Parallelogram: Represents input or output.
5. Arrows: Show the flow of execution.
Example of a Flowchart:
Suppose we want to design a program that checks if a number is even or odd. The flowchart will
look like this:
1. Start
2. Input the number
3. Check if the number is divisible by 2
o If Yes, print "Even"
o If No, print "Odd"
4. End
This visual representation makes it easy to understand how the program should work.
2. Pseudocode
Pseudocode is a way of writing a program in a simple, human-readable form before converting it
into actual code. It helps programmers focus on the logic without worrying about syntax.
Advantages of Pseudocode:
Helps in structuring the logic before writing actual code.
Makes it easier to communicate algorithms with non-programmers.
Reduces errors by allowing pre-checking of logic.
Acts as a blueprint for writing the final code.
Example of Pseudocode:
Let’s take the same example of checking if a number is even or odd.
START
INPUT number
IF number MOD 2 == 0 THEN
PRINT "Even"
9
Easy2Siksha
ELSE
PRINT "Odd"
END IF
STOP
This is a simple and clear way of describing the logic without using any specific programming
language syntax.
Comparison Between Flowcharts and Pseudocode
Feature
Flowchart
Pseudocode
Representation
Visual
Text-based
Readability
Easy for all
Better for programmers
Modifications
Difficult
Easier
Debugging
Moderate
High
Conclusion
Problem analysis is a crucial step in programming that ensures a clear understanding of the problem
before writing code. Tools like Flowcharts and Pseudocode help programmers design structured
solutions, making it easier to develop efficient programs. By using these tools, one can visualize
problems effectively, reduce errors, and create better solutions.
Understanding and practicing problem analysis helps programmers improve their problem-solving
skills and write better programs. Just like solving a puzzle, breaking a problem into smaller parts and
using the right tools makes it easier to find the correct solution.
SECTION-B
3. What is a Syntax Error? How is it different from a logical error? Give three examples of each of
them.
Ans: Syntax Errors and Logical Errors in C Programming
Programming is like writing instructions for a computer to follow. Just like how a sentence must
follow grammatical rules to be understood, a computer program must follow specific rules known
as "syntax." If a program does not follow these rules, it results in an error. Two common types of
errors in C programming are syntax errors and logical errors. Let’s understand them in detail with
examples.
10
Easy2Siksha
What is a Syntax Error?
A syntax error occurs when the rules of a programming language are not followed. It is similar to
making grammatical mistakes while writing a sentence in English. Just like a sentence with incorrect
grammar does not make sense, a program with syntax errors cannot be understood by the
compiler.
How does a Syntax Error Occur?
When we write a program, it must follow the correct structure and punctuation of the language. A
syntax error can occur if:
A semicolon (;) is missing at the end of a statement.
Parentheses, curly braces, or quotation marks are not correctly placed or closed.
A keyword or function name is misspelled.
A variable is used before it is declared.
Examples of Syntax Errors in C
Missing semicolon (;)
#include <stdio.h>
int main() {
printf("Hello, World!") // Missing semicolon
return 0;
}
Error: The compiler will report an error because the semicolon is missing after printf("Hello,
World!").
Misspelled keyword
#include <stdio.h>
int mian() { // 'main' is misspelled as 'mian'
printf("Hello");
return 0;
}
Error: The compiler will not recognize mian() as the main function and will generate an error.
Unmatched parentheses or brackets
#include <stdio.h>
int main() {
11
Easy2Siksha
printf("Hello, World!"; // Missing closing parenthesis )
return 0;
}
Error: The compiler expects a closing parenthesis ) before the semicolon.
How to Fix Syntax Errors?
Carefully read the compiler error messages. They usually tell you the line number where the
error occurred.
Check for missing or extra punctuation like semicolons, parentheses, and brackets.
Make sure all keywords are spelled correctly.
Declare variables before using them.
What is a Logical Error?
A logical error occurs when a program runs without crashing but produces the wrong output. Unlike
syntax errors, logical errors do not prevent the program from running, but they cause incorrect
results because of mistakes in the logic of the program.
How does a Logical Error Occur?
Logical errors happen when:
The wrong formula or operation is used in calculations.
Conditions in if statements are incorrect.
A loop does not iterate the expected number of times.
Variables are updated incorrectly.
Examples of Logical Errors in C
Incorrect formula in calculations
#include <stdio.h>
int main() {
int a = 5, b = 2;
int sum = a - b; // Should be a + b
printf("Sum: %d", sum);
return 0;
}
Error: The program subtracts instead of adding a and b, leading to the wrong result.
Incorrect condition in an if statement
12
Easy2Siksha
#include <stdio.h>
int main() {
int age = 20;
if (age > 18) {
printf("You are not eligible to vote."); // Wrong message
}
return 0;
}
Error: The condition is correct, but the message is wrong. The program should print "You are eligible
to vote."
Infinite loop due to incorrect condition
#include <stdio.h>
int main() {
int i = 1;
while (i != 10) {
printf("%d ", i);
i += 2; // i will never be exactly 10
}
return 0;
}
Error: Since i is increasing by 2, it will never be exactly 10, leading to an infinite loop.
How to Fix Logical Errors?
Use printf() statements to check variable values at different stages of the program.
Carefully analyze the logic and expected outcome of your program.
Use debugging tools to track variable changes and program flow.
Test your program with different inputs to see if it behaves as expected.
13
Easy2Siksha
Key Differences Between Syntax Errors and Logical Errors
Feature
Syntax Error
Logical Error
Definition
Violating the grammar rules of the
programming language.
A mistake in the program's logic that
produces incorrect results.
Detection
Detected by the compiler before
running the program.
Detected during program execution by observing
incorrect results.
Program Execution
The program does not compile or run.
The program runs but gives incorrect
output.
Example
Missing semicolon, misspelled
keywords.
Incorrect formulas, wrong conditions
in loops and if statements.
Analogy for Better Understanding
Think of programming like following a cooking recipe:
Syntax Error: If the recipe says "Add 2 eggs," but you forget to write "eggs" or spell it as
"egss," the recipe won't make sense. Similarly, a syntax error prevents the program from
running.
Logical Error: If the recipe says "Add 2 tablespoons of salt" instead of "2 teaspoons," the
food will taste bad but can still be cooked. Likewise, a logical error allows the program to run
but produces the wrong output.
Conclusion
Syntax errors and logical errors are common in programming, but they can be avoided with careful
coding and testing. Syntax errors are easier to fix because the compiler helps identify them, while
logical errors require thorough testing and debugging. Understanding the difference between these
errors is crucial for writing efficient and error-free programs.
4. With the help of examples, state the different operators in C.
Ans: Operators in C with Examples
Operators in C are special symbols that perform operations on variables and values. They help in
performing arithmetic calculations, comparisons, logical operations, and more. Understanding these
14
Easy2Siksha
operators is crucial for writing efficient C programs. Let's explore them in detail with simple
examples.
1. Arithmetic Operators
Arithmetic operators are used to perform basic mathematical operations.
Operator
Symbol
Example
Output
Addition
+
5 + 3
8
Subtraction
-
10 - 4
6
Multiplication
*
6 * 2
12
Division
/
8 / 2
4
Modulus
%
10 % 3
1
Example:
2. Relational (Comparison) Operators
These operators compare two values and return true (1) or false (0).
Operator
Meaning
Example
Output
==
Equal to
5 == 5
1 (true)
!=
Not equal to
5 != 3
1 (true)
>
Greater than
8 > 4
1
<
Less than
3 < 7
1
>=
Greater than or equal to
6 >= 6
1
<=
Less than or equal to
4 <= 5
1
15
Easy2Siksha
Example:
3. Logical Operators
Logical operators are used to combine multiple conditions.
Operator
Meaning
Example
&&
Logical AND
(x > 5) && (y < 10)
`
`
Logical OR
`(x > 5)
(y > 10)`
!
Logical NOT
!(x == y)
Example:
4. Bitwise Operators
Bitwise operators perform operations at the bit level.
Operator
Meaning
&
Bitwise AND
`
`
Bitwise OR
^
Bitwise XOR
<<
Left Shift
>>
Right Shift
16
Easy2Siksha
Example:
5. Assignment Operators
These are used to assign values to variables.
Operator
Example
Equivalent To
=
x = 5
Assign 5 to x
+=
x += 2
x = x + 2
-=
x -= 3
x = x - 3
*=
x *= 4
x = x * 4
/=
x /= 2
x = x / 2
%=
x %= 3
x = x % 3
6. Increment and Decrement Operators
Used to increase or decrease a variable’s value by 1.
Operator
Example
Equivalent To
++
x++
x = x + 1
--
x--
x = x - 1
Example:
17
Easy2Siksha
7. Conditional (Ternary) Operator
A shorthand for if-else statements.
Syntax:
condition ? value_if_true : value_if_false;
Example:
8. Special Operators
Size of Operator
Used to determine the size of a data type or variable.
Comma Operator (,)
Used to separate multiple expressions.
int a = (1, 2, 3); // a will be assigned 3
Pointer Operator (* and &)
Used in pointers to access memory addresses.
int a = 10;
int *ptr = &a; // Pointer to a
Conclusion
Operators in C help in performing various operations efficiently. Understanding them with examples
makes programming easier and more effective.
18
Easy2Siksha
SECTION-C
5. Write pseudo code for arranging numbers in a sorted way in an array.
Ans: Understanding Sorting and Its Importance
Sorting is a process of arranging data in a particular order, such as ascending (smallest to largest) or
descending (largest to smallest). In daily life, we sort things like books on a shelf, numbers in a
phone directory, or even arranging clothes in a wardrobe. In programming, sorting helps in efficient
searching, organizing data, and performing calculations faster.
Sorting an Array in Ascending Order
To arrange numbers in a sorted way inside an array, we need to compare the numbers and arrange
them properly. There are several sorting techniques, but we will use Bubble Sort, which is one of
the simplest and easiest to understand.
How Bubble Sort Works (Using a Simple Analogy)
Imagine you have a row of boxes, each containing a different number, and you need to arrange
them from smallest to largest. You compare two boxes at a time and swap them if they are in the
wrong order. You keep repeating this until all boxes are arranged properly. This process is similar to
how Bubble Sort works.
Steps to Sort an Array (Using Bubble Sort)
1. Start with an unsorted array (e.g., [5, 3, 8, 2, 1]).
2. Compare the first two elements. If the first is greater than the second, swap them.
3. Move to the next pair and repeat the comparison and swapping if necessary.
4. Continue this process until the largest number moves to the last position.
5. Repeat the process for the remaining elements, ignoring the last sorted numbers.
6. Keep repeating until no more swaps are needed, which means the array is sorted.
Pseudo Code for Sorting an Array Using Bubble Sort
19
Easy2Siksha
Step-by-Step Explanation of the Pseudo Code
Step 1: Input the Array Size and Elements
First, we ask the user to enter the number of elements in the array.
The user then inputs all the numbers one by one.
20
Easy2Siksha
Step 2: Sorting the Array (Using Bubble Sort)
We use two loops:
o The outer loop controls the number of passes.
o The inner loop compares adjacent elements and swaps them if needed.
We continue swapping until the array is sorted.
Step 3: Display the Sorted Array
After sorting, we print the elements in ascending order.
Example Walkthrough
Let’s say we have an array:
[5, 3, 8, 2, 1]
Pass 1:
Compare 5 and 3 → Swap → [3, 5, 8, 2, 1]
Compare 5 and 8 → No Swap
Compare 8 and 2 → Swap → [3, 5, 2, 8, 1]
Compare 8 and 1 → Swap → [3, 5, 2, 1, 8]
Pass 2:
Compare 3 and 5 → No Swap
Compare 5 and 2 → Swap → [3, 2, 5, 1, 8]
Compare 5 and 1 → Swap → [3, 2, 1, 5, 8]
Pass 3:
Compare 3 and 2 → Swap → [2, 3, 1, 5, 8]
Compare 3 and 1 → Swap → [2, 1, 3, 5, 8]
Pass 4:
Compare 2 and 1 → Swap → [1, 2, 3, 5, 8]
Now, the array is sorted.
Advantages of Bubble Sort
Easy to understand and implement.
No extra space required (works within the same array).
Good for small datasets.
21
Easy2Siksha
Disadvantages of Bubble Sort
Not efficient for large arrays (takes more time compared to advanced sorting algorithms like
Quick Sort or Merge Sort).
Too many swaps slow down the sorting process.
Alternative Sorting Methods
1. Selection Sort Find the smallest element and place it in the first position, then repeat for
remaining elements.
2. Insertion Sort Take one element at a time and place it in its correct position.
3. Merge Sort Divide the array into smaller parts, sort them, and merge back.
4. Quick Sort Pick a "pivot" and arrange elements around it recursively.
For large datasets, Merge Sort and Quick Sort are faster.
Conclusion
Sorting an array is an important concept in programming. Bubble Sort, though simple, helps in
understanding the basics of how sorting works. Once you grasp this, you can explore more efficient
sorting techniques. The provided pseudo-code gives a clear idea of how to implement sorting in a
step-by-step manner.
6. Explain any five string handling functions using different examples.
Ans: String Functions C
String Handling Functions in C
Strings in C are a sequence of characters stored in an array, ending with a special character called
the null character (\0). Since C does not have a built-in string data type like some other
programming languages, it uses character arrays to handle strings. The C Standard Library provides
several functions to perform operations on strings.
Here, we will discuss five important string-handling functions in C with examples.
1. strlen() Finding the Length of a String
Purpose:
This function is used to determine the number of characters in a string, excluding the null character
(\0).
22
Easy2Siksha
Syntax:
size_t strlen(const char *str);
Example:
Explanation:
strlen(myString) calculates the length of "Hello, World!", which is 13 characters.
The function does not count the null character at the end.
2. strcpy() Copying One String into Another
Purpose:
This function copies the contents of one string into another.
Syntax:
char *strcpy(char *destination, const char *source);
Example:
Explanation:
strcpy(copy, original); copies the content of original into copy.
Make sure the destination array is large enough to store the copied string.
23
Easy2Siksha
3. strcat() Concatenating Two Strings
Purpose:
This function is used to join (concatenate) two strings together.
Syntax:
char *strcat(char *destination, const char *source);
Example:
Explanation:
strcat(first, second); adds second to the end of first.
The first array must have enough space to store both strings.
4. strcmp() Comparing Two Strings
Purpose:
This function compares two strings character by character and returns:
0 if both strings are equal
A positive value if the first string is greater
A negative value if the second string is greater
Syntax:
int strcmp(const char *str1, const char *str2);
Example:
24
Easy2Siksha
Explanation:
Since "Apple" comes before "Banana" in alphabetical order, the function returns a negative
value.
5. strrev() Reversing a String (Not a Standard Function)
Purpose:
This function reverses a given string. Though strrev() is available in some compilers, it is not a
standard C function. If it is unavailable, you can implement it manually.
Example:
Explanation:
This function swaps the first and last characters, then the second and second-last characters,
and so on.
The loop runs until half of the string is reversed.
25
Easy2Siksha
Conclusion
These five string functions in C help in performing common operations like measuring length,
copying, concatenation, comparison, and reversing. Understanding and using these functions
properly can make string handling much easier in C programming. Always ensure that the
destination arrays have enough space when using functions like strcpy() and strcat() to prevent
memory overflow errors.
SECTION-D
7. What are the different ways of passing arguments to a function? Explain with the help of an
example.
Ans: Different Ways of Passing Arguments to a Function in C
Introduction
In the C programming language, functions help break a program into smaller, manageable parts.
When we use functions, we often need to send data to them. This data is passed as arguments (also
called parameters). There are two primary ways to pass arguments to a function in C:
1. Call by Value
2. Call by Reference
Each method has its own way of handling data and affects how changes made inside the function
reflect outside the function.
1. Call by Value
Explanation
In the call by value method, a copy of the actual value is passed to the function. This means that any
changes made inside the function do not affect the original value.
Imagine you are making a photocopy of an important document. If you write or modify something
on the photocopy, the original document remains unchanged. Similarly, in call by value, the
function works with a duplicate of the variable.
Example:
26
Easy2Siksha
Output:
Before function call: 10
After function call: 10
Explanation:
The value 10 is copied and sent to the function changeValue.
Inside changeValue, num is modified to 20, but this does not affect x in main.
The original variable x remains 10 even after the function call.
When to Use Call by Value:
When we do not want the function to modify the original variable.
When working with small variables like integers, floats, and characters.
2. Call by Reference
Explanation
In the call by reference method, the actual memory address of the variable is passed to the
function. This allows the function to modify the original variable.
Think of it like giving your friend a key to your house. They can enter and rearrange things inside
your home. Similarly, when we pass a variable by reference, the function can directly change its
value in memory.
Example:
27
Easy2Siksha
Output:
Before function call: 10
After function call: 20
Explanation:
Instead of sending a copy, we send the memory address of x.
Inside changeValue, *num refers to the actual value stored at that address, so modifying
*num modifies x directly.
After the function call, x has changed to 20.
When to Use Call by Reference:
When we want the function to modify the original variable.
When working with large data structures (like arrays) to avoid copying large amounts of
data.
Differences Between Call by Value and Call by Reference
Feature
Call by Value
Call by Reference
Passes
A copy of the variable
The memory address of the variable
Affects Original Value?
No
Yes
Used For
Small variables
Large data structures
Efficiency
Less efficient if large data needs
copying
More efficient for large data
28
Easy2Siksha
Call by Reference with Arrays
When working with arrays, we always use call by reference because an array name in C is a pointer
to its first element.
Example:
Output:
Before function call: 1
After function call: 100
Explanation:
Even though we didn't use pointers explicitly, arrays are passed by reference.
The function modifyArray changes the first element, and this change is reflected in main.
Conclusion
Both call by value and call by reference have their advantages and should be used appropriately
based on the requirement. If you want to protect the original variable from changes, use call by
value. If you need to modify the original variable or avoid unnecessary memory usage, use call by
reference.
Understanding these concepts will help you write efficient and effective programs in C. Keep
practicing with different examples to get a strong grasp of the topic!
8. Explain the scope and lifetime of a variable in the context of different storage classes.
Ans: Understanding the Scope and Lifetime of a Variable in C
In the C programming language, variables are fundamental building blocks that store data.
However, their accessibility and lifespan in a program depend on how and where they are declared.
29
Easy2Siksha
This is controlled by storage classes, which define the scope (where the variable can be accessed)
and lifetime (how long the variable exists in memory). In this explanation, we will break down these
concepts in a simple and easy-to-understand way.
1. What is Scope?
The scope of a variable refers to the part of the program where the variable can be accessed. In C,
there are three main types of scope:
Local Scope
Global Scope
Block Scope
Local Scope
A variable is said to have a local scope if it is declared inside a function or a block of code (inside {}
braces). It can only be accessed within that function or block.
Example:
Explanation:
The variable x is local to myFunction(), meaning it can only be accessed within that function.
Trying to access x outside myFunction() will cause an error.
Global Scope
A global variable is declared outside of all functions, usually at the top of the program. It can be
accessed by any function in the program.
Example:
30
Easy2Siksha
Explanation:
globalVar is declared outside all functions, making it accessible from both main() and
myFunction().
Block Scope
A block-scoped variable is declared inside a specific block {} and is accessible only within that block.
Example:
Explanation:
The variable y exists only inside the {} block.
It is destroyed after the block ends.
2. What is Lifetime?
The lifetime of a variable refers to how long it remains in memory before being destroyed. This
depends on the storage class used when declaring the variable.
The four types of storage classes in C are:
1. Automatic (auto)
2. Static (static)
3. External (extern)
4. Register (register)
31
Easy2Siksha
Automatic Storage Class (auto)
Variables declared inside a function by default are automatic.
They exist only while the function is running and are destroyed when the function ends.
Example:
Explanation:
The variable a exists only when demo() runs and is destroyed afterward.
Static Storage Class (static)
A static variable retains its value even after the function exits.
It is initialized only once and preserves its value between function calls.
Example:
Explanation:
The variable count is only initialized once and retains its value across multiple calls to
counter().
External Storage Class (extern)
An extern variable is declared in one file but defined in another.
32
Easy2Siksha
It helps in sharing global variables between multiple files.
Example: File1.c:
File2.c:
Explanation:
extern allows globalVar to be shared between File1.c and File2.c.
Register Storage Class (register)
The register keyword suggests storing the variable in a CPU register instead of RAM for
faster access.
It is mainly used for frequently accessed variables like loop counters.
Example:
Explanation:
i is a register variable, making loop execution faster.
33
Easy2Siksha
Summary
Storage Class
Scope
Lifetime
Purpose
auto
Local
Function execution
Default storage class
static
Local or global
Entire program
execution
Retains value between function calls
extern
Global
Entire program
execution
Used for global variables across
multiple files
register
Local
Function execution
Faster access using CPU registers
By understanding scope and lifetime, you can efficiently use variables in C to optimize memory
usage and program performance!
Note: This Answer Paper is totally Solved by Ai (Artificial Intelligence) So if You find Any Error Or Mistake . Give us a
Feedback related Error , We will Definitely Try To solve this Problem Or Error.